﻿using StarryEdge.Core.Device;
using StarryEdge.Core.Enums;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarryEdge.Devices.Tool
{
    public class ConnectionHelper
    {
        public static byte[] SendToRead(ICommunication com, IProtocol protocol, byte[] bytes, int count)
        {
            Stopwatch stopwatch = new Stopwatch();
            bytes = protocol.Serialize(bytes);
            com.Send(bytes);
            List<byte> list = new List<byte>();
            byte[] buffer = com.Receive();
            list.AddRange(buffer);
            stopwatch.Start();
            while (!protocol.Verify(list))
            {
                if (stopwatch.ElapsedMilliseconds > 2000)
                {
                    stopwatch.Stop();
                    throw new Exception("报文响应超时!!!");
                }
                Thread.Sleep(5);
                buffer = com.Receive();
                list.AddRange(buffer);
            }
            return protocol.Deserialize(list);
        }
    }
}
